package com.yc.login.web;

import com.yc.login.web.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        final HttpSession session = request.getSession();
        final Object loginedUser = session.getAttribute("loginedUser");
        if(loginedUser == null){
            //  判断当前请求的类型
            final String accept = request.getHeader("Accept");
            if (accept.startsWith("application/json")){
                // ajax 请求 => json
                // 请求转发
                final RequestDispatcher rd = request.getRequestDispatcher("/user/myinfo");
                rd.forward(request,response);
            } else {
                // 表单请求  => 跳转页面  /login.html => 实现配置
                // 响应重定向
                response.sendRedirect("/login.html");
            }
            // 不允许访问
            return false;
        } else {
            // 允许访问目标资源
            return true;
        }
    }
}
